# -*- coding: utf-8 -*-
from PIL import Image
import numpy as np
from barcode.writer import ImageWriter
import barcode
import os
import cv2
import copy
import io
import random

#生成一维码的类型的种类
"""
[u'code39', u'code128', u'ean', u'ean13', u'ean8', u'gs1', u'gtin',
 u'isbn', u'isbn10', u'isbn13', u'issn', u'jan', u'pzn', u'upc', u'upca']
"""


#8个一维码进行2*4的方式合并存成一张图，参数:码类型、文件数量
def barcode_fun(return_width, return_heigh =10):
    all_type = [u'code39', u'code128', u'ean', u'ean13', u'ean8', u'gs1', u'gtin',
                u'isbn', u'isbn10', u'isbn13', u'issn', u'jan', u'pzn', u'upc', u'upca']
    barcode_type = np.random.choice(all_type)
    r_num = random.randint(100000000000000, 999999999999999)
    EAN = barcode.get_barcode_class(barcode_type) #设置生成一维码的类型
    image = EAN(str(r_num), writer=ImageWriter())
    # buffer = io.BytesIO()
    # image.save(buffer, format="jpeg")
    buf = image.save("a")
    
    pil_image = Image.open(buf)
    # pil_image = Image.open("a.png")

    final_image = pil_image.convert('RGBA')
    image_array = np.frombuffer(final_image.tobytes(), dtype=np.uint8)
    image_array = image_array.reshape((final_image.size[1], final_image.size[0], 4))
    cv_image = copy.copy(image_array[:,:,:3])
    gray_image = cv2.cvtColor(cv_image, cv2.COLOR_RGB2GRAY)
    bin_image = cv2.threshold(gray_image, 60, 255, cv2.THRESH_BINARY_INV)[1]
 
    row_sum = np.sum(bin_image, axis=1)


    row_start = np.where(row_sum>0)[0][0]
    crop_bin = bin_image[row_start:row_start+return_heigh,  :]
    col_sum = np.sum(crop_bin, axis=0)
    row_index = np.where(col_sum>0)[0]
    col_start = row_index[0]
    col_end = row_index[-1]
    
    crop_image = final_image.crop((col_start, row_start, col_end, row_start+return_heigh))
    if col_end-col_start > return_width:
        return_image = crop_image.crop((0,0,return_width,return_heigh) )
    else:
        return_image = Image.new('RGBA', (return_width, return_heigh), (0, 0, 0, 0))
        for i in range(int(np.ceil(return_width / crop_image.size[0]))):
            if (i+1) * crop_image.size[0] > return_width:
                width_p = crop_image.size[0]- ((i+1) * crop_image.size[0] - return_width)
                return_image.paste(crop_image.crop((0,0,int(width_p), return_heigh)), ( i * crop_image.size[0], 0))
            else:
                return_image.paste(crop_image, ( i * crop_image.size[0], 0))
    return return_image


#主函数设置需要生成码类型的目录，生成相应码。
if __name__=="__main__":

    
    return_image = barcode_fun(2000, 20)
    return_image.save("a.png")

"""
# if( (i+1)%8 == 0 ):
        #     base_img0 = Image.open('./code/'+barcode_type+'/'+str(i-7)+'.png')
        #     base_img1 = Image.open('./code/'+barcode_type+'/'+str(i-6)+'.png')
        #     base_img2 = Image.open('./code/'+barcode_type+'/'+str(i-5)+'.png')
        #     base_img3 = Image.open('./code/'+barcode_type+'/'+str(i-4)+'.png')
        #     base_img4 = Image.open('./code/'+barcode_type+'/'+str(i-3)+'.png')
        #     base_img5 = Image.open('./code/'+barcode_type+'/'+str(i-2)+'.png')
        #     base_img6 = Image.open('./code/'+barcode_type+'/'+str(i-1)+'.png')
        #     base_img7 = Image.open('./code/'+barcode_type+'/'+str(i)+'.png')
        #     x = base_img0.size[0]
        #     y = base_img0.size[1]
        #     target = Image.new('RGBA', (2*x,4*y), color=0)
        #     target.paste(base_img0,(0,0,x,y))
        #     target.paste(base_img1,(x,0,2*x,y))
        #     target.paste(base_img2,(0,y,x,2*y))
        #     target.paste(base_img3,(x,y,2*x,2*y))
        #     target.paste(base_img4,(0,2*y,x,3*y))
        #     target.paste(base_img5,(x,2*y,2*x,3*y))
        #     target.paste(base_img6,(0,3*y,x,4*y))
        #     target.paste(base_img7,(x,3*y,2*x,4*y))
        #     target.save('./code/'+barcode_type+'/'+barcode_type+"_"+str((i+1)/8)+'.png')
        #     os.system("rm "+'./code/'+barcode_type+'/'+str(i-7)+'.png')
        #     os.system("rm "+'./code/'+barcode_type+'/'+str(i-6)+'.png')
        #     os.system("rm "+'./code/'+barcode_type+'/'+str(i-5)+'.png')
        #     os.system("rm "+'./code/'+barcode_type+'/'+str(i-4)+'.png')
        #     os.system("rm "+'./code/'+barcode_type+'/'+str(i-3)+'.png')
        #     os.system("rm "+'./code/'+barcode_type+'/'+str(i-2)+'.png')
        #     os.system("rm "+'./code/'+barcode_type+'/'+str(i-1)+'.png')
        #     os.system("rm "+'./code/'+barcode_type+'/'+str(i)+'.png')

"""